package com.origin.src.datasource.sharding.algorithm;

import com.google.common.base.Strings;
import org.apache.shardingsphere.infra.datanode.DataNodeInfo;
import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Collection;
import java.util.zip.CRC32;
import java.util.zip.Checksum;

public class Base64Crc32ChecksumModShardingAlgorithm extends ChecksumModShardingAlgorithm {

    /**
     * Get auto tables amount.
     *
     * @return the auto tables amount
     */
    @Override
    public Checksum getChecksum() {
        return null;
    }

    /**
     * Sharding.
     *
     * @param availableTargetNames available data sources or table names
     * @param shardingValue        sharding value
     * @return sharding result for data source or table name
     */
    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Comparable<?>> shardingValue) {
        String key = String.valueOf(shardingValue.getValue());
        Checksum crc32 = new CRC32();
        crc32.update(Base64.getEncoder().encode(key.getBytes(StandardCharsets.UTF_8)));
        String suffix = Long.toString(crc32.getValue() % availableTargetNames.size());
        DataNodeInfo dataNodeInfo = shardingValue.getDataNodeInfo();
        return dataNodeInfo.getPrefix() + Strings.padStart(suffix, dataNodeInfo.getSuffixMinLength(), dataNodeInfo.getPaddingChar());
    }

    @Override
    public String getType() {
        return "BASE64_CRC32_MOD";
    }
}
